Lumen & Gesso / website · lumengesso.com / app / api / admin / orders / [id] / send-to-printer / route.ts
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | import { getCustomerUser } from '@/app/lib/lumen-auth'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { isAdmin } from '@/app/lib/admin'; |
| 5 | import { prodigiFetch } from '@/app/lib/prodigi'; |
| 6 | import { prodigiItem } from '@/app/lib/prodigi-skus'; |
| 7 | import { sendEmail } from '@/app/lib/email'; |
| 8 | import { env } from '@/app/lib/env'; |
| 9 | import { displayOrderId } from '@/app/lib/orders'; |
| 10 | import { inProductionHtml } from '@/app/lib/order-emails'; |
| 11 | import { generateMagicLink } from '@/app/lib/magic-link'; |
| 12 | |
| 13 | export const runtime = 'nodejs'; |
| 14 | export const dynamic = 'force-dynamic'; |
| 15 | |
| 16 | // Admin-triggered "send to printer" step. Customer approval moves the |
| 17 | // order to `approved` but does NOT auto-fire the Prodigi order — admin |
| 18 | // always does one final review (right print file, right shipping |
| 19 | // address, no oddities) and clicks this route to commit. On success |
| 20 | // the order moves to `in_production` and the customer gets the |
| 21 | // "your portrait is on its way to print" email. |
| 22 | export async function POST( |
| 23 | req: NextRequest, |
| 24 | ctx: { params: Promise<{ id: string }> }, |
| 25 | ) { |
| 26 | const { id } = await ctx.params; |
| 27 | |
| 28 | const user = await getCustomerUser(); |
| 29 | if (!user || !isAdmin(user.email)) { |
| 30 | return NextResponse.json({ error: 'forbidden' }, { status: 403 }); |
| 31 | } |
| 32 | |
| 33 | const admin = commerceDb(); |
| 34 | const { data: order } = await admin |
| 35 | .from('orders') |
| 36 | .select('id, user_email, status, config, shipping_address, prodigi_order_id, current_generation_id') |
| 37 | .eq('id', id) |
| 38 | .single(); |
| 39 | if (!order) return NextResponse.json({ error: 'order not found' }, { status: 404 }); |
| 40 | if (order.status !== 'approved') { |
| 41 | return NextResponse.json({ |
| 42 | error: `Cannot send to printer — order status is "${order.status}". This action only works after the customer has approved their proof (status: approved).`, |
| 43 | }, { status: 409 }); |
| 44 | } |
| 45 | if (order.prodigi_order_id) { |
| 46 | return NextResponse.json({ |
| 47 | error: `This order already has a Prodigi reference (${order.prodigi_order_id}). Refusing to create a duplicate.`, |
| 48 | }, { status: 409 }); |
| 49 | } |
| 50 | |
| 51 | // Look up the published generation's clean URL (Prodigi prints this). |
| 52 | const proofQuery = admin |
| 53 | .from('generations') |
| 54 | .select('clean_url') |
| 55 | .eq('order_id', id); |
| 56 | const { data: pubGen } = await (order.current_generation_id |
| 57 | ? proofQuery.eq('id', order.current_generation_id) |
| 58 | : proofQuery.eq('published', true)).single(); |
| 59 | if (!pubGen?.clean_url) { |
| 60 | return NextResponse.json({ |
| 61 | error: 'No published generation found for this order. Publish a proof first.', |
| 62 | }, { status: 409 }); |
| 63 | } |
| 64 | |
| 65 | // Resolve the SKU + colour/wrap attributes from the customer's config. |
| 66 | const cfg = order.config as { |
| 67 | productId: 'matted' | 'canvas' | 'classic' | 'stretched'; |
| 68 | size: string; |
| 69 | frame: string; |
| 70 | matteId?: string; |
| 71 | wrap?: string; |
| 72 | }; |
| 73 | const { sku, attributes } = prodigiItem({ |
| 74 | productId: cfg.productId, |
| 75 | sizeId: cfg.size, |
| 76 | frameId: cfg.frame, |
| 77 | matteId: cfg.matteId, |
| 78 | wrapId: cfg.wrap, |
| 79 | }); |
| 80 | |
| 81 | // Build the Prodigi recipient block from the shipping address Stripe |
| 82 | // collected at checkout. Without it we can't print — fail fast. |
| 83 | type ShippingAddr = { |
| 84 | name?: string; |
| 85 | address?: { |
| 86 | line1?: string; |
| 87 | line2?: string | null; |
| 88 | city?: string; |
| 89 | state?: string; |
| 90 | postal_code?: string; |
| 91 | country?: string; |
| 92 | }; |
| 93 | }; |
| 94 | const shipping = order.shipping_address as ShippingAddr | null; |
| 95 | if (!shipping?.name || !shipping.address?.line1) { |
| 96 | return NextResponse.json({ |
| 97 | error: 'Shipping address is missing on this order — cannot send to print without it.', |
| 98 | }, { status: 409 }); |
| 99 | } |
| 100 | const recipient = { |
| 101 | name: shipping.name, |
| 102 | address: { |
| 103 | line1: shipping.address.line1, |
| 104 | line2: shipping.address.line2 ?? undefined, |
| 105 | townOrCity: shipping.address.city, |
| 106 | stateOrCounty: shipping.address.state, |
| 107 | postalOrZipCode: shipping.address.postal_code, |
| 108 | countryCode: shipping.address.country, |
| 109 | }, |
| 110 | }; |
| 111 | |
| 112 | // Create the Prodigi order. |
| 113 | let prodigiOrderId: string | null = null; |
| 114 | try { |
| 115 | const prodigiRes = await prodigiFetch('Orders', { |
| 116 | method: 'POST', |
| 117 | body: JSON.stringify({ |
| 118 | shippingMethod: 'Standard', |
| 119 | recipient, |
| 120 | items: [{ |
| 121 | sku, |
| 122 | copies: 1, |
| 123 | sizing: 'fillPrintArea', |
| 124 | attributes, |
| 125 | assets: [{ printArea: 'default', url: pubGen.clean_url }], |
| 126 | }], |
| 127 | callbackUrl: `${env.site.url()}/api/webhooks/prodigi/${process.env.PRODIGI_WEBHOOK_TOKEN}`, |
| 128 | }), |
| 129 | }); |
| 130 | const prodigiJson = await prodigiRes.json() as { order?: { id?: string }; outcome?: string }; |
| 131 | if (!prodigiRes.ok || !prodigiJson.order?.id) { |
| 132 | console.error('[send-to-printer] Prodigi rejected', prodigiRes.status, prodigiJson); |
| 133 | return NextResponse.json({ |
| 134 | error: `Prodigi rejected the order (${prodigiRes.status}): ${prodigiJson?.outcome ?? 'unknown error'}. Nothing was charged or shipped; the order stays at "approved" so you can retry.`, |
| 135 | }, { status: 502 }); |
| 136 | } |
| 137 | prodigiOrderId = prodigiJson.order.id; |
| 138 | } catch (e) { |
| 139 | console.error('[send-to-printer] Prodigi error', e); |
| 140 | const msg = e instanceof Error ? e.message : 'Prodigi request failed'; |
| 141 | return NextResponse.json({ |
| 142 | error: `Prodigi request failed: ${msg}. Order stays at "approved" — try again.`, |
| 143 | }, { status: 502 }); |
| 144 | } |
| 145 | |
| 146 | // Commit the transition. |
| 147 | await admin.from('orders').update({ |
| 148 | status: 'in_production', |
| 149 | prodigi_order_id: prodigiOrderId, |
| 150 | }).eq('id', id); |
| 151 | |
| 152 | // Customer confirmation email — magic-link to the order page so |
| 153 | // they land signed in if they click through. |
| 154 | const reviewPath = `/orders/${id}#review`; |
| 155 | const orderLink = await generateMagicLink(order.user_email, reviewPath); |
| 156 | const fallbackUrl = `${env.site.url()}${reviewPath}`; |
| 157 | await sendEmail({ |
| 158 | to: order.user_email, |
| 159 | subject: `In production — ${displayOrderId(id)}`, |
| 160 | html: inProductionHtml(id, orderLink ?? fallbackUrl, prodigiOrderId), |
| 161 | text: `Your portrait is on its way to print. We'll email you again when it ships. Once it arrives, you can leave a star rating, write a review, and share a photo from your order page. View your order: ${orderLink ?? fallbackUrl}`, |
| 162 | }).catch(() => {}); |
| 163 | |
| 164 | return NextResponse.json({ ok: true, prodigiOrderId }); |
| 165 | } |